#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <set>
#include "Common.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"

using namespace LogModule;
class Command
{
public:


    Command()
    {
        _Executable_Commands.insert("ls");
        _Executable_Commands.insert("ll");
        _Executable_Commands.insert("pwd");
        _Executable_Commands.insert("whoami");
        _Executable_Commands.insert("ps -axj");
        _Executable_Commands.insert("ps -aL");
    }

    bool IsSafeCommand(const std::string& cmd)
    {
        auto iter = _Executable_Commands.find(cmd);
        return iter != _Executable_Commands.end();
    }

    std::string Execute(const std::string& cmd, InetAddr& addr)
    {
        if(!IsSafeCommand(cmd))
        {
            return std::string("Permission denied");
        }

        std::string name = addr.StringAddr();

        FILE* fp = popen(cmd.c_str(), "r");
        if(fp == nullptr)
        {
            return std::string("popen error, the command: ") + cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line;
        }
        pclose(fp);
        res = name + " execute command: " + cmd + " the result is: \n" + res;
        //LOG(LogLevel::DEBUG) << res;
        return res;
    }

    ~Command()
    {}

private:
    std::set<std::string> _Executable_Commands;
};